package com.mhh.selary.backend.task;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author mhh
 * @date 2020-11-09 10:08:43
 */
@Component
public class ScheduleTaskPool {

    @Autowired
    private AsyncTaskExecutor asyncTaskExecutor;

    @Autowired
    private InitPropConfigTask initPropConfigTask;

    private ScheduledExecutorService schedule;

    @PostConstruct
    public void init() {
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("ScheduleTaskPool-%d").setDaemon(true).build();
        schedule = new ScheduledThreadPoolExecutor(40, threadFactory, new ThreadPoolExecutor.AbortPolicy());
        schedule.schedule(initPropConfigTask, 5000, TimeUnit.MILLISECONDS);
    }

    public void schedule(Runnable runnable, Long delay) {
        schedule.schedule(runnable, delay, TimeUnit.MILLISECONDS);
    }

    public <T> Future<T> execute(Callable<T> callable) {
        return asyncTaskExecutor.submit(callable);
    }

    public void execute(Runnable runnable) {
        asyncTaskExecutor.execute(runnable);
    }

    public boolean isShutdown() {
        return schedule.isShutdown();
    }
}
